var backgroundLoggingFeature; // shorthand for logging to the console 
//without having to type the whole attribute name : chrome.extension.getBackgroundPage().console.log(xxx)

/////////////////////////////////// INITIALIZATION
$(document).ready(function () {  
    backgroundLoggingFeature=chrome.extension.getBackgroundPage().console;
  
      	
    $("#tabs").tabs().addClass('ui-tabs-vertical ui-helper-clearfix');
    $("#tabs li").removeClass('ui-corner-top').addClass('ui-corner-left');

    $("[id^='inputUrl']").bind("change",function() {
        //we have 2 text input fields which must appear to user as being one and the same element
        //in order to achieve this, whenever there's a change on one of those fields' value, we copy the value 
        //to the others' fields' copies
        var newInputValue=$(this).val();
        $("[id^='inputUrl']").val(newInputValue);
    });
    
    
/* Triggers the feed query */    
    $("[id^='requestFeed']").click(function() { 
        
        var url=$("#inputUrl1").val();
        var data=$.parseJSON($("#inputJSON").val());

        backgroundLoggingFeature.log("Requesting feed at url '"+url+"' with textarea data provided by the user");
        
        $("[id^='lastQueryDetails']").removeClass("feedRequestNOK").addClass("feedRequestOK").text(getCurrentHour()+": Request sent...");
        
        
        $.post(
            url,            
            data
            )
        .success(function(data) {
            backgroundLoggingFeature.log("Ajax query successful");
            
            $("#outputJSON").val(data);
            $("#tabs").tabs('select', '#tabs-2');
            
            $("[id^='lastQueryDetails']").removeClass("feedRequestNOK").addClass("feedRequestOK").text(getCurrentHour()+": Response received.");
            
        })
        .error(function(data) {
            $("[id^='lastQueryDetails']").removeClass("feedRequestOK").addClass("feedRequestNOK").text(getCurrentHour()+ ": Failed with status '"+data.status+"'");        
            backgroundLoggingFeature.log("Ajax query failed with status:"+data.statusText+"********"+data.status+"********"+data);
        });
       
       
    });
    
    
    backgroundLoggingFeature.log("labJSONFeeds.js: initialized.. ");        
    
});

function getCurrentHour() {
//returns a string containing the current system hour in format HOURS:MINUTES:SECONDS
    var currentDate=new Date();
    return sprintf("%02d:%02d:%02d",currentDate.getHours(),currentDate.getMinutes(),currentDate.getSeconds());
    
}